<!--
 * @Author: Wangtao
 * @Date: 2022-08-09 17:23:08
 * @LastEditors: Wangtao
 * @LastEditTime: 2022-09-21 16:55:42
-->
<template>
  <div
    :class="{ 'call-card-box': isCallCard, 'call-record-box': !isCallCard }"
    class="detail mc-call-variable"
    v-loading="loading"
  >
    <div class="card-customer-info">
      <div class="card-customer-info-box">
        <div class="customer-box-top">
          <div class="customer-box-top-left">
            <div class="name">
              {{ computedCardInfo && computedCardInfo.customerName ? computedCardInfo.customerName : '未知客户' }}
            </div>
            <div class="oprate">
              <el-tooltip :show-after="500" class="box-item" effect="dark" content="外呼" placement="top">
                <div class="btn circular call" v-show="allowOutbound" @click="dialout">
                  <i class="MC_iconfont MC_icon-hujiaohuojieting"></i>
                </div>
              </el-tooltip>
              <!-- <el-tooltip :show-after="500" class="box-item" effect="dark" content="发短信" placement="top">
                <div class="btn circular sms"><i class="MC_iconfont MC_icon-zixun"></i></div>
              </el-tooltip> -->
            </div>
          </div>
          <div class="customer-box-top-right">
            <el-tooltip
              :show-after="500"
              class="box-item"
              effect="dark"
              content="更换此通话记录绑定客户"
              placement="top"
            >
              <div class="btn" @click="selectCustomer"><i class="MC_iconfont MC_icon-fanzhuan"></i></div>
            </el-tooltip>
          </div>
        </div>
        <div class="customer-box-bottom" v-if="isCallCard">
          <div class="phone-info">电话号：{{ cardInfo && cardInfo.customerPhone }}</div>
          <!-- <div>服务号：123456789 售前</div>
          <div>服务组：产品/云客服</div> -->
          <div>
            客户归属地：{{ cardInfo && cardInfo.customerCountry ? cardInfo.customerCountry : '未知地点' }}
            {{ cardInfo && cardInfo.customerProvince ? cardInfo.customerProvince : '' }}
          </div>
        </div>
      </div>
    </div>
    <div class="card-tab">
      <card-tabs
        :callRcordInfo="callRcordInfo"
        :tabs="tabs"
        :scene="scene"
        :cardInfo="cardInfo"
        :customerList="customerList"
      ></card-tabs>
    </div>
    <move-dialog
      :visible.sync="selectCustomerDialog.visible"
      :close-on-click-modal="false"
      width="720px"
      title="选择客户"
    >
      <customerList
        ref="customerListRef"
        v-if="selectCustomerDialog.visible"
        :getType="'phone'"
        :phone="cardInfo.customerPhone"
      ></customerList>
      <template #footer>
        <el-button type="default" @click="selectCustomerDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="slsectCustomerSave">保存</el-button>
      </template>
    </move-dialog>
  </div>
</template>

<script lang="ts">
import { defineComponent, watch, reactive, toRefs, onBeforeMount, computed, onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'

import { getCdrDetail } from '@app/base/apis/call'

import cardTabs from '@app/call-center/views/recent-calls/component/card-tabs.vue'
import { callCardModule } from '@/common/store/modules/call-card'
import { callStateModule } from '@/common/store/modules/call-state'

import { getCustomerByMobile } from '@app/base/apis/call'
import mcCache from '@/common/utils/mc-get-cache'

import { cusDetail } from '@app/customer/apis/pool'

import moveDialog from '@/common/components/move-dialog/index.vue'

import customerList from '@app/call-center/views/recent-calls/component/tab-component/customDetail/customer-list.vue'

import { cdrCustomerRelation } from '@app/base/apis/call'
import { ElMessage } from 'element-plus'
export default defineComponent({
  name: 'RecentCalls',
  components: {
    cardTabs,
    moveDialog,
    customerList
  },
  props: {
    scene: {
      type: String,
      default: 'callcard'
    },
    callId: {
      type: String,
      default: ''
    },
    allowOutbound: {
      type: Boolean,
      default: true
    }
  },
  // ----------------生命周期-----------------------
  setup(props: any, { emit }) {
    const customerListRef: any = ref(null)
    // ----------------传入属性-----------------------
    // ----------------内部属性-----------------------
    const route: any = useRoute()
    const CALLCARD = callCardModule()
    const CALLSTATE = callStateModule()
    const state: any = reactive({
      tabs: [
        { name: 'callDetail', label: '通话详情' },
        { name: 'callDynamicBi', label: '服务小计' },
        { name: 'customDetail', label: '客户信息' }
      ],
      cardInfo: {},
      customerList: [],
      loading: false,
      cardIndex: 0,
      callRcordInfo: {},
      selectCustomerDialog: {
        visible: false
      },
      selectCustomer() {
        state.selectCustomerDialog.visible = true
      },
      async slsectCustomerSave() {
        if (customerListRef.value.currentRow) {
          const customerId = customerListRef.value.currentRow._id
          const customerInfo = customerListRef.value.currentRowInfo
          const callId = props.callId || route.params.id
          const res = await cdrCustomerRelation({
            callId: callId,
            customerId: customerId,
            isUpdate: true
          })
          state.customerList = [customerInfo]
          state.cardInfo.customerName = customerInfo.customerName || '未填写名称'
          ElMessage.success('切换成功')
          // 修改卡片关联关系
          CALLCARD.updateCardInfo(callId, 'customerId', customerId)
          CALLCARD.updateCardInfo(callId, 'customerName', state.cardInfo.customerName)
          state.selectCustomerDialog.visible = false
        } else {
          ElMessage.warning('请选择客户')
        }
      }
    })

    const methods = reactive({
      tabChange(name: string) {
        emit('tabChange', name)
      },
      dialout() {
        if (state.cardInfo && state.cardInfo.customerPhone) {
          CALLSTATE.dialOut(state.cardInfo.customerPhone)
        }
      },
      async getCallDetailById(id: string) {
        const query = { id }
        const res = await getCdrDetail(query)
      },
      // 根据场景值处理卡片数据
      async initCardInfo() {
        // 刷新重新获取卡片信息
        await CALLCARD.getCardListByLocal()
        state.loading = true
        if (props.scene === 'callcard') {
          // 通话卡片信息
          const CARDID = route.params.id
          const currentCardInfo = await CALLCARD.getCurrentCardInfoById(CARDID)
          state.cardIndex = currentCardInfo.index
          state.cardInfo = currentCardInfo
          // 客户信息
          if (currentCardInfo.customerId) {
            const customerRes: any = await cusDetail(currentCardInfo.customerId)
            if (customerRes.data) {
              // 未被删除 展示客户信息即可
              state.customerList = [customerRes.data]
              state.cardInfo.customerName = customerRes.data.customerName
              // 更新卡片客户信息 除了手机号
              CALLCARD.updateCardInfo(CARDID, 'customerName', customerRes.data.customerName)
            } else {
              // 绑定客户已被删除 重新通过手机号匹配
              const res = await getCustomerByMobile({ mobile: currentCardInfo.customerPhone, type: '1' })
              const customerList = res.data.list || []
              CALLCARD.updateCardInfo(CARDID, 'customeId', '')
              state.customerList = customerList
              if (customerList.length === 1) {
                state.cardInfo.customerName = customerList[0].customerName
              } else if (customerList.length > 1) {
                state.cardInfo.customerName = '对应多个客户'
              } else {
                state.cardInfo.customerName = '未知客户'
              }
              CALLCARD.updateCardInfo(CARDID, 'customerName', state.cardInfo.customerName)
            }
          } else {
            // 未关联
            const res = await getCustomerByMobile({ mobile: currentCardInfo.customerPhone, type: '1' })
            const customerList = res.data.list || []
            state.customerList = customerList
            if (customerList.length === 1) {
              state.cardInfo.customerName = customerList[0].customerName
            } else if (customerList.length > 1) {
              state.cardInfo.customerName = '对应多个客户'
            } else {
              state.cardInfo.customerName = '未知客户'
            }
            CALLCARD.updateCardInfo(CARDID, 'customerName', state.cardInfo.customerName)
          }
        }

        if (props.scene === 'callrecord') {
          const CARDID = props.callId
          const res = await getCdrDetail({ id: CARDID })
          if (res.success) {
            state.callRcordInfo = res.data
            if (state.callRcordInfo.customerId) {
              const customerRes: any = await cusDetail(state.callRcordInfo.customerId)
              if (customerRes.success) {
                if (customerRes.data) {
                  state.customerList = [customerRes.data]
                  state.cardInfo.customerName = customerRes.data.customerName || '未填写名称'
                }
                state.cardInfo.customerPhone = state.callRcordInfo.customerNumber
                state.cardInfo.superUniqueId = state.callRcordInfo._id
              }
            } else {
              state.customerList = []
              state.cardInfo.customerName = '未知客户'
              state.cardInfo.customerPhone = state.callRcordInfo.customerNumber
              state.cardInfo.superUniqueId = state.callRcordInfo._id
            }
          }
        }
        state.loading = false
      }
    })

    onBeforeMount(() => {
      if (props.scene === 'callcard') {
        state.tabs = [
          { name: 'callDynamicBi', label: '服务小计' },
          { name: 'customDetail', label: '客户信息' }
        ]
      } else {
        state.tabs = [
          { name: 'callDetail', label: '通话详情' },
          { name: 'callDynamicBi', label: '服务小计' },
          { name: 'customDetail', label: '客户信息' }
        ]
      }
    })

    onMounted(() => {
      mcCache.$getCache('globalFieldCache', 'hasObj', '', '', '', '', 'field') // 全局字段
      mcCache.$getCache('cusInfo', 'hasObj', '', '', '', '', 'field') // 客户信息
      mcCache.$getCache('region') // 地区
      mcCache.$getCache('serviceLabels') // 服务标签
    })

    // ----------------计算属性-----------------------
    const computedCardInfo = computed(() => {
      if (props.scene === 'callcard') {
        return CALLCARD.list[state.cardIndex]
      } else {
        return state.cardInfo
      }
    })

    const isCallCard = computed(() => {
      return props.scene === 'callcard'
    })

    // ----------------监听方法-----------------------
    // 卡片触发方式
    watch(
      () => route.params,
      async (params) => {
        if (params && params.id) {
          await methods.initCardInfo()
        }
      },
      { immediate: true }
    )
    // 通话记录触发方式
    watch(
      () => props.callId,
      async (id) => {
        if (id) {
          await methods.initCardInfo()
        }
      },
      { immediate: true }
    )
    // ----------------调用方法-----------------------
    return {
      ...toRefs(methods),
      ...toRefs(state),
      computedCardInfo,
      isCallCard,
      customerListRef
    }
  }
})
</script>
<style lang="stylus">
.RecentCalls-box
  .el-scrollbar__bar.is-vertical
    width 4px
    .el-scrollbar__thumb
      background-color var(--mc-gray4-color)
      opacity 1
</style>
<style lang="stylus" scoped>
.call-card-box
  padding 24px 24px 0
  .card-customer-info
    padding 0
.call-record-box
  padding 0px 0 24px
.detail
  width 100%
  height 100%
  box-sizing border-box
  display: flex
  flex-direction: column
  justify-content: flex-start
  .card-tab
    flex:auto
    overflow: hidden;
    position relative
  .btn
    width 24px
    height 24px
    background red
    display flex
    align-items center
    justify-content center
    margin-left 16px
    background-color var(--mc-gray3-color)
    color rgba(0, 0, 0, 0.88)
    border-radius 4px
    .MC_iconfont
      font-size 16px
  .circular
    border-radius 50%
    color white
  .card-customer-info
    box-sizing border-box
    width 100%
    flex:0 0 auto
    .card-customer-info-box
      width 100%
      padding 16px 20px 16px
      box-sizing border-box
      background-color var(--el-fill-color-lighter)
      .customer-box-bottom
        margin-top 12px
        display flex
        .phone-info
          color rgba(0, 0, 0, 0.88)
        > div
          font-weight 400
          font-size 14px
          margin-right 40px
          color rgba(0, 0, 0, 0.6)
      .customer-box-top
        display flex
        justify-content space-between
        align-items center
        .customer-box-top-left
          display flex
          align-items center
          .name
            font-weight 500
            font-size 20px
          .oprate
            display flex
            .call
              background-color var(--mc-call-color-connect)
            .sms
              background-color var(--mc-call-color-ringing)
</style>
